package com.atXiao.food.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class FileNameGeneratorUtil {

    // 日期格式
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    // 生成随机字符的范围
    private static final String RANDOM_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    // 生成文件名的方法
    public static String generateFileName(String originalFileName) {
        // 获取当前时间戳
        String timestamp = dateFormat.format(new Date());
        // 获取文件扩展名
        String fileExtension = getFileExtension(originalFileName);
        // 生成随机字符
        String randomString = generateRandomString(8);
        // 组合文件名
        return timestamp + "_" + randomString + "." + fileExtension;
    }

    // 获取文件扩展名的方法
    private static String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex == -1) {
            // 文件没有扩展名
            return "";
        }
        return fileName.substring(lastDotIndex + 1);
    }

    // 生成指定长度的随机字符的方法
    private static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder randomStringBuilder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            char randomChar = RANDOM_CHARACTERS.charAt(random.nextInt(RANDOM_CHARACTERS.length()));
            randomStringBuilder.append(randomChar);
        }
        return randomStringBuilder.toString();
    }
}
